package com.liang.book.controller;

import com.liang.book.constant.Constant;
import com.liang.book.model.Result;
import com.liang.book.model.UserInfo;
import com.liang.book.service.UserService;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping(value = "/login",produces = "application/json")
    public Result<String> login(String userName, @RequestParam("password") String passWord, HttpSession session) {
       log.info("用户登录 username：{},password:{},",userName,passWord);
        //1.参数校验
        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength(passWord)) {
            return Result.fail("用户名或密码不能为空");
        }
        //2.验证用户名和密码
        UserInfo userInfo = userService.queryUserByName(userName);
        if (userInfo==null || userInfo.getId()<0) {
            return Result.fail("用户名不存在");
        }
        if(!passWord.equals(userInfo.getPassWord())) {
            return Result.fail("账号或密码错误");
        }
//        if (!"zhangsan".equals(userName) || !"123456".equals(passWord)) {
//            return "用户名或密码错误";
//        }
        // 3.存session 默认存在内存中
        userInfo.setPassWord("");//存在服务器端的
        session.setAttribute(Constant.USER_SESSION_KEY, userInfo);
        return Result.success("");

    }
}